package com.dreamer.repository.pyramid;

import com.dreamer.domain.pyramid.PyramidUser;
import com.dreamer.domain.pyramid.PyramidUserVo;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;
import ps.mx.otter.utils.SearchParameter;
import ps.mx.otter.utils.dao.hibernate.HibernateBaseDAO;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Repository("pyramidUserDAO")
public class PyramidUserDAO extends HibernateBaseDAO<PyramidUser> {

    private Session getCurrentSession() {
        return getSessionFactory().getCurrentSession();
    }

    public List<PyramidUser> searchAllByPage(SearchParameter<PyramidUser> p) {
        return super.searchEntityByPage(p, (t) -> {
            Example example = Example.create(t.getEntity()).enableLike(MatchMode.ANYWHERE);
            Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(getClazz());
            criteria.add(example);
            return criteria;
        }, (o)-> true);
    }

    public void save(PyramidUser transientInstance) {

        try {
            getCurrentSession().save(transientInstance);

        } catch (RuntimeException re) {

            throw re;
        }
    }

    public void delete(PyramidUser persistentInstance) {
        try {
            getCurrentSession().delete(persistentInstance);

        } catch (RuntimeException re) {

            throw re;
        }
    }

    public PyramidUser findById(Integer id) {

        try {
            PyramidUser instance = (PyramidUser) getCurrentSession().get(
                    "com.dreamer.domain.pyramid.PyramidUser", id);
            return instance;
        } catch (RuntimeException re) {

            throw re;
        }
    }

    public PyramidUserVo findByIdVo(Integer id) {
        try {
            String hql = " select " +
                    " pu.id as id," +
                    " pu.userId as userId," +
                    " pu.pyramidId as pyramidId," +
                    " u.realName as realName," +
                    " u.mobile as mobile," +
                    " u.weixin as weixin," +
                    " p.checkpoint as checkpoint," +
                    " p.layerNumber as layerNumber," +
                    " p.info as info," +
                    " pu.createTime as createTime," +
                    " pu.updateTime as updateTime " +
                    " from PyramidUser pu " +
                    " left join User u on u.id = pu.userId " +
                    " left join Pyramid p on p.id = pu.pyramidId " +
                    " where 1=1 and pu.id="+id;
            Query query = getCurrentSession().createQuery(hql);
            List list = query.list();
            PyramidUserVo PUVO = new PyramidUserVo();
            for (int i = 0; i < list.size(); i++) {
                Object[] object = (Object[]) list.get(i);
                PUVO.setId((Integer) object[0]);
                PUVO.setUserId((Integer) object[1]);
                PUVO.setPyramidId((Integer) object[2]);
                PUVO.setRealName((String) object[3]);
                PUVO.setMobile((String) object[4]);
                PUVO.setWeixin((String) object[5]);
                PUVO.setCheckpoint((String) object[6]);
                PUVO.setLayerNumber((String) object[7]);
                PUVO.setInfo((String) object[8]);
                PUVO.setCreateTime((Date) object[9]);
                PUVO.setUpdateTime((Date) object[10]);
            }
            PyramidUserVo instance = PUVO;
            return instance;
        } catch (RuntimeException re) {

            throw re;
        }
    }

    public PyramidUser merge(PyramidUser detachedInstance) {
        try {
            PyramidUser result = (PyramidUser) getCurrentSession().merge(detachedInstance);
            return result;
        } catch (RuntimeException re) {

            throw re;
        }
    }

    public List<PyramidUser> findAll() {
        try {
            String queryString = "from PyramidUser";
            Query queryObject = getCurrentSession().createQuery(queryString);
            return queryObject.list();
        } catch (RuntimeException re) {
            throw re;
        }
    }

    //TODO 获取当前层的所有人数，一定要排序从小到大
    public List<PyramidUser> findPyramidUserByPyramidIdASE(Integer pyramidId){
        String hql = "from PyramidUser pu where pu.pyramid.id = :pyramidId order by pu.createTime asc";
        Query query = getCurrentSession().createQuery(hql);
        query.setParameter("pyramidId",pyramidId);
        return query.list();
    }



    //TODO 获取当前层的所有人数，一定要排序从小到大 ------根据虚拟位置
    public List<PyramidUser> findPyramidUserByPyramidIdAndPositionDesc(Integer pyramidId){
        String hql = "from PyramidUser pu where pu.pyramid.id = :pyramidId order by pu.position desc";
        Query query = getCurrentSession().createQuery(hql);
        query.setParameter("pyramidId",pyramidId);
        return query.list();
    }



    //TODO 判断当前用户是否存在PyramidUser里面：
    public List<PyramidUser> findPyramidUserByUserId(Integer userId){
        String hql = "from PyramidUser pu where pu.user.id = :userId";
        Query query = getCurrentSession().createQuery(hql);
        query.setParameter("userId",userId);
        return query.list();
    }

    public List<PyramidUser> findPyramidUserByUserIdObjList(Integer userId){
        String hql = "from PyramidUser pu where pu.user.id = :userId";
        Query query = getCurrentSession().createQuery(hql);
        query.setParameter("userId",userId);
        return query.list();
    }

    //TODO 判断当前用户是否存在PyramidUser里面：
    public PyramidUser findPyramidUserByUserIdObj(Integer userId){
        String hql = "from PyramidUser pu where pu.user.id = :userId";
        Query query = getCurrentSession().createQuery(hql);
        query.setParameter("userId",userId);
        return (PyramidUser)query.list().get(0);
    }

    //TODO 获取当前层中最后一个人
    public PyramidUser findPyramidUserByPyramidIdDESC(Integer pyramidId){
        String hql = "from PyramidUser pu where pu.pyramid.id = :pyramidId order by pu.createTime asc";
        Query query = getCurrentSession().createQuery(hql);
        query.setParameter("pyramidId",pyramidId);
        return (PyramidUser) query.list().get(0);
    }

    //TODO 获取当前层中最后一个人    -----根据虚拟的位置排
    public PyramidUser findPyramidUserByPyramidIdAndPositionASCLast(Integer pyramidId){
        String hql = "from PyramidUser pu where pu.pyramid.id = :pyramidId order by pu.position desc";
        Query query = getCurrentSession().createQuery(hql);
        query.setParameter("pyramidId",pyramidId);
        return (PyramidUser) query.list().get(0);
    }

    //todo 后台用户定位
    public List<PyramidUserVo> findPyramidVoAll(SearchParameter<PyramidUserVo> p) {
        List<PyramidUserVo> pyramidUserVoList = new ArrayList<>();
        StringBuffer stringBuffer = new StringBuffer();
        String hql = " select " +
                " pu.id as id," +
                " pu.userId as userId," +
                " pu.pyramidId as pyramidId," +
                " u.realName as realName," +
                " u.mobile as mobile," +
                " u.weixin as weixin," +
                " p.checkpoint as checkpoint," +
                " p.layerNumber as layerNumber," +
                " p.info as info," +
                " pu.createTime as createTime," +
                " pu.updateTime as updateTime " +
                " from PyramidUser pu " +
                " left join User u on u.id = pu.userId " +
                " left join Pyramid p on p.id = pu.pyramidId " +
                " where 1=1  ";
        stringBuffer.append(hql);
        if(!p.getEntity().getRealName().trim().equals("") && p.getEntity().getRealName() != null){
            String hql1 = " and u.realName like '%"+p.getEntity().getRealName()+"%' ";
            stringBuffer.append(hql1);
        }
        if(!p.getEntity().getMobile().trim().equals("") && p.getEntity().getMobile() != null) {
            String hql2 = " and u.mobile like '%" + p.getEntity().getMobile() + "%' ";
            stringBuffer.append(hql2);
        }
        if(!p.getEntity().getCheckpoint().trim().equals("") && p.getEntity().getCheckpoint() != null){
            String hql3 = " and p.checkpoint = "+p.getEntity().getCheckpoint();
            stringBuffer.append(hql3);
        }
        if(!p.getEntity().getLayerNumber().trim().equals("") && p.getEntity().getLayerNumber() != null){
            String hql4 = " and p.layerNumber = "+p.getEntity().getLayerNumber();
            stringBuffer.append(hql4);
        }
        Query query = getCurrentSession().createQuery(stringBuffer.toString());
        List list = query.list();
        for (int i = 0; i < list.size(); i++) {
            Object[] object = (Object[]) list.get(i);
            PyramidUserVo PUVO = new PyramidUserVo();
            PUVO.setId((Integer) object[0]);
            PUVO.setUserId((Integer) object[1]);
            PUVO.setPyramidId((Integer) object[2]);
            PUVO.setRealName((String) object[3]);
            PUVO.setMobile((String) object[4]);
            PUVO.setWeixin((String) object[5]);
            PUVO.setCheckpoint((String) object[6]);
            PUVO.setLayerNumber((String) object[7]);
            PUVO.setInfo((String) object[8]);
            PUVO.setCreateTime((Date) object[9]);
            PUVO.setUpdateTime((Date) object[10]);
            pyramidUserVoList.add(PUVO);
        }
        return pyramidUserVoList;
    }

}
